<template>
  <el-form ref="form" :model="form" :rules="rules">
    <el-form-item ref="phone" label="手机号" prop="phone">
      <el-input v-model="form.phone" placeholder="请输入手机号" autofocus />
    </el-form-item>
    <template v-if="signInType === 'code'">
      <el-form-item ref="code" label="验证码" prop="code">
        <el-input v-model="form.code" placeholder="请输入验证码" @keyup.enter.native="onSubmit">
          <send-code-btn
            slot="suffix"
            :phone="form.phone"
            class="m-r-10"
            @checkPhone="verifyPhone"
          />
        </el-input>
      </el-form-item>
      <el-form-item class="nlh">
        <span
          class="link el-link--primary"
          style="line-height: unset"
          @click="changeType('password')"
        >密码登录</span>
      </el-form-item>
    </template>
    <template v-if="signInType === 'password'">
      <el-form-item ref="password" label="密码" prop="password">
        <el-input
          v-model="form.password"
          placeholder="请输入密码"
          show-password
          @keyup.enter.native="onSubmit"
        />
      </el-form-item>
      <el-form-item class="nlh">
        <span
          class="link el-link--primary"
          style="line-height: unset"
          @click="changeType('code')"
        >验证码登录</span>
      </el-form-item>
    </template>
    <el-form-item>
      <el-button class="full" type="primary" @click="onSubmit" :loading="loading">登录并绑定</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapActions } from 'vuex';
import SendCodeBtn from '@/components/shared/SendCodeBtn';
import { formatUser } from '@/components/users/format';

export default {
  name: 'bind_existing_user_form', // 绑定已有用户
  components: { SendCodeBtn },
  data() {
    return {
      form: {
        phone: '', // 手机号
        code: '', // 验证码
        password: '', // 密码
      },
      rules: {
        phone: [{ validator: this.$va.phone, trigger: 'none' }],
        code: [{ validator: this.$va.code, trigger: 'none' }],
        password: [{ validator: this.$va.password, trigger: 'none' }],
      },
      signInType: 'code',
      loading: false, // 绑定中
    };
  },
  methods: {
    ...mapActions({
      setCurUser: 'setCurrentUser',
      removeCurUser: 'removeCurrentUser',
    }),
    // 修改登录类型
    changeType(type) {
      if (this.form.phone) this.$refs.form.validateField('phone'); // 当填写了手机号时，验证这个号码
      else this.$refs.phone.clearValidate(); // 当没有填写手机号时，清除验证提示
      if (this.$refs.password) this.$refs.password.resetField(); // 清除密码和验证提示
      if (this.$refs.code) this.$refs.code.resetField(); // 清除验证码和验证提示
      this.signInType = type;
    },
    // 触发验证手机号
    verifyPhone() { this.$refs.form.validateField('phone'); },
    // 提交表单
    onSubmit() {
      this.$refs.form.validate((valid, errs) => {
        if (valid) {
          this.loading = true;
          this.$api.users.signIn({
            phone: this.form.phone, // 手机号
            type: this.signInType, // 登录类型
            password: this.form.password, // 密码
            code: this.form.code, // 验证码
          }).then((res) => {
            this.setCurUser(formatUser(res.data));
            this.bindUser();
          }).catch(() => {})
            .then(() => { this.loading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
    // 绑定用户（自动获取用户token）
    bindUser() {
      this.$api.oauth.update({
        openId: this.$route.query.open_id,
        type: this.$route.query.type,
      }).then(() => {
        this.$message.success('绑定成功');
        const redirect = localStorage.getItem('otherSignIn');
        localStorage.removeItem('otherSignIn');
        this.$router.push(redirect || '/');
      }).catch(() => this.removeCurUser())
        .then(() => { this.loading = false; });
    },
  },
};
</script>

<style></style>
